package com.jshongli.myapplication.inspect.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseFragment;
import com.jshongli.myapplication.common.callback.MyCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.CroodUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.model.inspect.SignBean;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Request;

@SuppressLint("ValidFragment")
public class PatrolSignFragment extends BaseFragment {
    String pId;

    public PatrolSignFragment(String pId) {
        this.pId = pId;
    }

    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;


    List<SignBean.DATA> mData = new ArrayList<>();
    BaseQuickAdapter<SignBean.DATA, BaseViewHolder> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.recy_layout;
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initView() {
        super.initView();

        mRefreshLayout.setColorSchemeResources(R.color.refresh_blue,
                R.color.refresh_red, R.color.refresh_blue, R.color.refresh_red);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                load();
            }
        });

        load();
//        initRecy();
    }

    //region HTTP -- 获取签到记录
    public void load() {

        String url = URLUtils.URLNoToken("manageAPI/bizPoint/getListByPatrol");
        Map<String, String> map = new HashMap<>();
        map.put("patrolId", pId);

        OkHttpUtils
                .get()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .params(map)
                .tag(this)
                .build()
                .execute(new MyCallback<SignBean>(mContext) {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        mRefreshLayout.setRefreshing(true);
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        mRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onSuccess(SignBean response) {
                        if(response.data!=null){
                            mData = response.data;
                        }

                        if(mAdapter == null){
                            initRecy();
                        }else {
                            mAdapter.setNewData(mData);
                        }

                    }
                });
    }
    //endregion

    private void initRecy() {
        mAdapter = new BaseQuickAdapter<SignBean.DATA, BaseViewHolder>(R.layout.list_qd_process_item, mData) {
            @Override
            protected void convert(BaseViewHolder helper, SignBean.DATA item) {
                helper.setText(R.id.tv_tm, item.pileNum)
                        .setText(R.id.tv_address, item.address);



                if(item.bc == null)
                {
                    helper.setGone(R.id.signview, false);
                    helper.setVisible(R.id.nonesignview, true);
                    helper.setBackgroundRes(R.id.tv_tm,R.drawable.circle_btn_red);
                }else {
                    if (item.bc.picPath != null && item.bc.picPath.length() > 0) {
                        helper.setVisible(R.id.ll_qdzp, true);
                        NineGridView nineGrid = helper.getView(R.id.nineGrid);

                        List<String> pics = new ArrayList<>();
                        pics.add(item.bc.picPath);
                        setPics(pics, nineGrid);
                    } else {
                        helper.setGone(R.id.ll_qdzp, false);
                    }
                    helper.setVisible(R.id.signview, true);
                    helper.setGone(R.id.nonesignview, false);
                    helper.setBackgroundRes(R.id.tv_tm,R.drawable.circle_btn_blue);
                    helper.setText(R.id.tv_zjd, item.bc.cable)
                            .setText(R.id.tv_qdsj, item.bc.createTime)
                            .setText(R.id.tv_szwz, item.bc.lonLat);
                }

                helper.getView(R.id.tv_szwz).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        List<String> split= Arrays.asList(item.lonLat.split(","));
                        showBottomDialog(split.get(1),split.get(0));
                    }
                });


            }
        };
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_view, null);
        mAdapter.setEmptyView(emptyView);


        recy.setAdapter(mAdapter);
        recy.setLayoutManager(new LinearLayoutManager(mContext));
    }

    //region NineGridView -- 显示图片
    private void setPics(List<String> pics, NineGridView nineGrid) {

        if (pics.size() > 0) {
            ArrayList<ImageInfo> imageInfos = new ArrayList<>();
            if (pics != null) {
                for (String pic : pics) {
                    ImageInfo info = new ImageInfo();
                    Log.e("11111",URLUtils.XCXJiMg(pic));
                    info.setThumbnailUrl(URLUtils.SignIMg(pic));
                    info.setBigImageUrl(URLUtils.SignIMg(pic));
                    imageInfos.add(info);
                }

            }
            nineGrid.setSingleImageRatio(1.5f);
            nineGrid.setGridSpacing(15);
            nineGrid.setAdapter(new NineGridViewClickAdapter(mActivity, imageInfos));

        } else {
            nineGrid.setVisibility(View.GONE);
        }
    }
    //endregion

    //region 点击导航弹出选择
    private void showBottomDialog(String lat, String lng) {
        //1、使用Dialog、设置style
        Dialog dialog = new Dialog(mContext, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(mContext, R.layout.dialog_navi_layout, null);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

        final LatLng baidupoint = CroodUtils.gcj02_To_Bd09(Double.valueOf(lat), Double.valueOf(lng));

        dialog.findViewById(R.id.tv_bai).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AppManager.isAvilible(mContext, "com.baidu.BaiduMap")) {//传入指定应用包名
                    try {
                        Intent intent = Intent.getIntent("intent://map/direction?" +
                                "destination=latlng:" + baidupoint.latitude + "," + baidupoint.longitude + "|name:我的目的地" +        //终点
                                "&mode=driving&" +          //导航路线方式
                                "&src=appname#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    //market为路径，id为包名
                    //显示手机上所有的market商店
                    ToastUtils.show(mContext, "您尚未安装百度地图");

                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                        startActivity(intent);
                    }
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tv_gao).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AppManager.isAvilible(mContext, "com.autonavi.minimap")) {
                    try {
                        Intent intent = Intent.getIntent("androidamap://navi?sourceApplication=BIG BOX 24&poiname=我的目的地&lat=" + lat + "&lon=" + lng + "&dev=0");
                        mContext.startActivity(intent);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.show(mContext, "您尚未安装高德地图");
                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }
    //endregion
}
